import axios from 'axios'
import { message } from '@/utils/message'
import store from '@/store'
import {getToken, removeToken} from '@/utils/auth'
import define from '@/utils/define'
import { encrypt } from "@/utils/ende";

import { format, add } from "date-fns";
import getters from '@/store/getters'
const baseUrl = getters.baseUrl
// const baseUrl = window.location.host
// http://192.168.2.247:9000
// http://8.130.71.166:9000

// create an axios instance
const service = axios.create({
  // baseURL:baseUrl.indexOf('http') > -1 ? baseUrl: ('http://' + baseUrl + '/LabWebApi/'),//process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL:process.env.VUE_APP_BASE_API, // url = base url + request url
  // bserUrl: baseUrl,
  withCredentials: false, // send cookies when cross-domain requests
  timeout: define.timeout, // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.url = 'http://' + store.getters.baseUrl + config.url
    console.log(config.url)
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
      let d = new Date();
      config.headers["timestamp"] = encrypt(
        format(
          add(d, { minutes: d.getTimezoneOffset() + 480 }),
          "yyyyMMddHHmmss"
        )
      );
    }
    if (config.method == 'get') {
      config.params = config.data
    }
    let timestamp = Date.parse(new Date()) / 1000
    if (config.url.indexOf('?') > -1) {
      config.url += `&n=${timestamp}`
    } else {
      config.url += `?n=${timestamp}`
    }
    if (config.params && config.params.downFile) {
      config.responseType = "blob"
    } else if ( config.url.indexOf('Point/ImportExamPointFromExcel') > -1 ||
      config.url.indexOf('School/ImportSchoolClassFromExcel') > -1 ||
      config.url.indexOf('School/ImportSchoolStudentsFromExcel') > -1||
    config.url.indexOf('School/ImportExamSchoolFromExcel') > -1) {
      config.responseType = "blob"
    } else {
      delete  config.responseType
    }
    return config
  },
  error => {
    if (process.env.NODE_ENV === 'development') {
      console.log(error)
    }
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    let config = response.config
    let url = config.url
    // 特殊接口处理
    if (config.params && config.params.downFile && res) {
      return response
    }
    if (response.headers['message'] && ( url.indexOf('Point/ImportExamPointFromExcel') > -1 ||
      config.url.indexOf('School/ImportSchoolClassFromExcel') > -1 ||
      config.url.indexOf('School/ImportSchoolStudentsFromExcel') > -1||
      config.url.indexOf('School/ImportExamSchoolFromExcel') > -1)) {
      return response
    }
    if (res.Result.Code !== 200) {
      message({
        message: res.Result.Msg || '请求出错，请重试',
        type: 'error',
        duration: 1500,
        onClose: () => {
          if (url.indexOf('/api/oauth/Login') < 0 && url.indexOf('/api/oauth/LockScreen') < 0 && ( res.Result.Code === 300 || res.Result.Code === 603)) {
            //  603: Token验证失败res
            store.dispatch('user/resetToken').then(() => {
              if (window.location.pathname.indexOf('login') > -1) return
              setTimeout(() => { location.reload() }, 100);
            })
          }
        }
      })
      return Promise.reject(new Error(res.Result.Msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    if (process.env.NODE_ENV === 'development') {
      console.log(error) // for debug
    }

    if (error.response.data.code === 1) {
      message({
        message: error.response.data.msg,
        type: 'error',
        duration: 1500
      })
      store.dispatch('user/resetToken').then(() => {
        if (window.location.pathname.indexOf('login') > -1) return
        setTimeout(() => { location.reload() }, 100);
      })
    } else {
      if (error.response.status === 406) {
        console.log(2134)
        return Promise.reject(error.response)
      } else {
        message({
          message: error.response.headers['message'] ? decodeURIComponent(error.response.headers['message']) :'请求出错，请重试',
          type: 'error',
          duration: 1500
        })
        return Promise.reject(error)
      }
    }
  }
)

export default service
